package com.dayu.utils;

import com.dayu.common.config.RuoYiConfig;
import com.dayu.common.constant.Constants;
import com.dayu.common.utils.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码 + 文字  生成
 * @author HK
 */
public class BarCodeUtils {

    /*条码宽度*/
    private static final int WIDTH = 180;
    /*条码高度*/
    private static final int HEIGHT = 30;

    /**
     * 设置 条码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.CHARACTER_SET, "utf-8");
        }
    };

    /**
     * 生成 图片缓冲
     * @param vaNumber
     * @return
     */
    public static BufferedImage getBarCode(String vaNumber) {

        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     * 获取图片链接 只有条码的条码链接
     * @param orderNum 条码值
     * @return
     */
    public static String getBarCodeUrl(String orderNum) {

        BufferedImage image = BarCodeUtils.getBarCode(orderNum);
        String uploadDir = RuoYiConfig.getProfile() + "/barCode";
        String fileName = "/" + orderNum + ".png";
        File dirFile = new File(uploadDir);
        if(!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(uploadDir + fileName);
        if(!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            ImageIO.write(image, "png", new File(uploadDir + fileName));
            int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
            String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
            String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + fileName;
            return pathFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
